

package io.wongxd.demo.page.emo.ui.page

import android.app.Activity.RESULT_OK
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import io.modifier.basic.emo.photo.activity.PhotoClipperActivity
import io.modifier.basic.emo.photo.activity.PhotoClipperResult
import io.modifier.basic.emo.photo.activity.PhotoPickResult
import io.modifier.basic.emo.photo.activity.PhotoPickerActivity
import io.modifier.basic.emo.photo.activity.getPhotoClipperResult
import io.modifier.basic.emo.photo.activity.getPhotoPickResult
import io.modifier.basic.emo.photo.coil.CoilMediaPhotoProviderFactory
import io.modifier.basic.emo.photo.coil.CoilPhotoProvider
import io.modifier.basic.emo.photo.ui.PhotoThumbnailWithViewer
import io.modifier.basic.emo.scheme.ComposeScheme
import coil.compose.AsyncImage
import io.wongxd.demo.page.emo.EmoMainActivity
import io.wongxd.demo.page.emo.config.SchemeConst
import io.wongxd.demo.page.emo.config.runQuietly
import io.wongxd.demo.page.emo.config.schemeBuilder
import io.wongxd.demo.page.emo.ui.CommonItem
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList

@ComposeScheme(
    action = SchemeConst.SCHEME_ACTION_PHOTO,
    alternativeHosts = [EmoMainActivity::class]
)
@Composable
fun PhotoPage() {
    OnlyBackListPage(
        title = "Photo"
    ) {
        item {
            CommonItem("Photo Viewer") {
                schemeBuilder(SchemeConst.SCHEME_ACTION_PHOTO_VIEWER).runQuietly()
            }
        }

        item {
            CommonItem("Photo Picker") {
                schemeBuilder(SchemeConst.SCHEME_ACTION_PHOTO_PICKER).runQuietly()
            }
        }

        item {
            CommonItem("Photo Clipper") {
                schemeBuilder(SchemeConst.SCHEME_ACTION_PHOTO_CLIPPER).runQuietly()
            }
        }

//        item {
//            val context = LocalContext.current
//            val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.GetMultipleContents(), onResult = { uris ->
//                if (uris.isNotEmpty()) {
//                    val photoProviders = uris.map {
//                        PhotoShot(
//                            PdfPhotoProvider(it),
//                            null,
//                            null,
//                            null
//                        )
//                    }
//                    val intent = PhotoViewerActivity.intentOf(context, PhotoViewerActivity::class.java, photoProviders, 0)
//                    context.startActivity(intent)
//                }
//            })
//            CommonItem("PDF Multi Viewer") {
//                launcher.launch("application/pdf")
//            }
//        }

//        item {
//            val context = LocalContext.current
//            val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent(), onResult = { uri ->
//                if (uri != null) {
//                    val bundle = Bundle().apply {
//                        putParcelable("uri", uri)
//                    }
//                    val intent = PdfActivity.intentOf(context, PdfActivity::class.java, bundle, TestBundlePdfDataSourceFactory::class.java)
//                    context.startActivity(intent)
//                }
//            })
//            CommonItem("PDF Reader With Editing") {
//                launcher.launch("application/pdf")
//            }
//        }

//        item {
//            val state = remember {
//                mutableStateOf<PdfThumbPhoto?>(null)
//            }
//            val context = LocalContext.current
//            val launcher = rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent(), onResult = { uri ->
//                if (uri != null) {
//                    state.value = PdfThumbPhoto(TestPdfDataSource(context.applicationContext, uri))
//                }
//            })
//            Column {
//                CommonItem("PDF Reader Thumb") {
//                    launcher.launch("application/pdf")
//                }
//                Box(modifier = Modifier
//                    .width(100.dp)
//                    .height(141.dp)) {
//                    state.value?.Compose(
//                        contentScale = ContentScale.Fit,
//                        isContainerDimenExactly = true,
//                        onSuccess = null,
//                        onError = null
//                    )
//                }
//
//            }
//
//        }
    }
}

@ComposeScheme(
    action = SchemeConst.SCHEME_ACTION_PHOTO_VIEWER,
    alternativeHosts = [EmoMainActivity::class]
)
@Composable
fun PhotoViewerPage() {
    OnlyBackListPage(
        title = "Photo Viewer"
    ) {
        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "file:///android_asset/test.png".toUri(),
                            ratio = 0.0125f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        )
                    )
                )
            }
        }

        item {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, vertical = 20.dp)
            ) {
                PhotoThumbnailWithViewer(
                    images = persistentListOf(
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9136/1yn0KLFwy6Vb0nE6Sg.png".toUri(),
                            ratio = 1.379f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/8779/6WY7guGLeGfp0KK6Sb.jpeg".toUri(),
                            ratio = 0.749f
                        ),
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 1f
                        )
                    )
                )
            }
        }
    }
}


@ComposeScheme(
    action = SchemeConst.SCHEME_ACTION_PHOTO_PICKER,
    alternativeHosts = [EmoMainActivity::class]
)
@Composable
fun PhotoPickerPage() {
    val pickResult = remember {
        mutableStateOf<PhotoPickResult?>(null)
    }

    val pickLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == RESULT_OK) {
            it.data?.getPhotoPickResult()?.let { ret ->
                pickResult.value = ret
            }
        }
    }

    OnlyBackListPage(
        title = "Photo Viewer"
    ) {
        item(key = "pick-photo") {
            val context = LocalContext.current
            CommonItem("Pick Photo") {
                pickLauncher.launch(
                    PhotoPickerActivity.intentOf(
                        context,
                        CoilMediaPhotoProviderFactory::class.java,
                        pickedItems = arrayListOf<Uri>().apply { pickResult.value?.list?.mapTo(this) { it.uri } }
                    )
                )
            }
        }

        val result = pickResult.value
        if (result != null && result.list.isNotEmpty()) {
            item(key = result.list.map { it.id }.joinToString(",")) {
                val images = remember(pickResult) {
                    result.list.map {
                        CoilPhotoProvider(
                            it.uri,
                            ratio = it.ratio()
                        )
                    }.toPersistentList()
                }
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 20.dp, vertical = 20.dp)
                ) {
                    Text(text = "原图：${result.isOriginOpen}")

                    PhotoThumbnailWithViewer(
                        images = images
                    )
                }
            }
        }
    }
}

@ComposeScheme(
    action = SchemeConst.SCHEME_ACTION_PHOTO_CLIPPER,
    alternativeHosts = [EmoMainActivity::class]
)
@Composable
fun PhotoClipperPage() {
    val clipperResult = remember {
        mutableStateOf<PhotoClipperResult?>(null)
    }

    val pickLauncher = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it.resultCode == RESULT_OK) {
            it.data?.getPhotoClipperResult()?.let { ret ->
                clipperResult.value = ret
            }
        }
    }

    OnlyBackListPage(
        title = "Photo Clipper"
    ) {
        item(key = "clipper-photo") {
            val context = LocalContext.current
            CommonItem("Clip Photo") {
                pickLauncher.launch(
                    PhotoClipperActivity.intentOf(
                        context,
                        CoilPhotoProvider(
                            "https://weread-picture-1258476243.file.myqcloud.com/9979/31y68oGufDGL3zQ6TT.jpg".toUri(),
                            ratio = 0f
                        )
                    )
                )
            }
        }

        val result = clipperResult.value
        if (result != null) {
            item(key = result.uri.toString()) {
                AsyncImage(model = result.uri, contentDescription = "")
            }
        }
    }
}

//class TestPdfDataSource(val context: Context, val uri: Uri) : PdfDataSource {
//
//    override val title: StateFlow<String>
//        get() = MutableStateFlow(uri.fileName(context) ?: "")
//
//    override val downloadProgress: StateFlow<Int>
//        get() = MutableStateFlow(-1)
//
//
//    override fun readInitIndex(context: Context): Int {
//        return EmoKvInstance.getInt("pdf_index_${uri}", 0)
//    }
//
//    override fun readInitOffset(context: Context): Int {
//        return EmoKvInstance.getInt("pdf_offset_${uri}", 0)
//    }
//
//    override suspend fun getFileDescriptor(context: Context): ParcelFileDescriptor? {
//        return context.contentResolver.openFileDescriptor(uri, "r")
//    }
//
//    override suspend fun saveIndexAndOffset(index: Int, offset: Int) {
//        EmoKvInstance.put("pdf_index_${uri}", index)
//        EmoKvInstance.put("pdf_offset_${uri}", offset)
//    }
//
//    override fun supportEdit(page: Int): Boolean {
//        return true
//    }
//
//    override suspend fun saveEditLayers(page: Int, layers: PersistentList<EditLayer>) {
//        EmoKvInstance.put("pdf_editing_${uri}_${page}".toByteArray(), layers.map { it.serialize() }.let {
//            ProtoBuf.encodeToByteArray(EditLayersStoreInfo(it))
//        })
//    }
//
//    override suspend fun loadEditLayers(page: Int): PersistentList<EditLayer> {
//        return EmoKvInstance.get("pdf_editing_${uri}_${page}".toByteArray())?.let {
//            ProtoBuf.decodeFromByteArray<EditLayersStoreInfo>(it).list.mapNotNull { value ->
//                EditLayerDeserializeFactory.deserialize(value)
//            }
//        }?.toPersistentList() ?: persistentListOf()
//    }
//}
//
//@Serializable
//class EditLayersStoreInfo(
//    @ProtoNumber(1)
//    val list: List<ByteArray>
//)
//
//class TestBundlePdfDataSourceFactory : BundlePdfDataSourceFactory {
//    override fun factory(context: Context, bundle: Bundle): PdfDataSource {
//        val uri = bundle.getParcelable<Uri>("uri") ?: throw RuntimeException("uri is not provided")
//        return TestPdfDataSource(context, uri)
//    }
//
//}